package goodenglish.infrastructure.repository.db;

import goodenglish.infrastructure.Config;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {
	// 用来把Connection绑定到当前线程上的变量
	private static ThreadLocal<Connection> tl = new ThreadLocal<Connection>();

	/**
	 * 根据数据库的默认连接参数获取数据库的Connection对象，并绑定到当前线程上
	 * 
	 * @return 成功，返回Connection对象，否则返回null
	 */
	public static Connection getTxConnection() {
		Connection conn = tl.get(); // 先从当前线程上取出连接实例

		if (null == conn) { // 如果当前线程上没有Connection的实例
			conn = getConnection(); // 从连接池中取出一个连接实例
			tl.set(conn); // 把它绑定到当前线程上
		}
		return conn;
	}

	/**
	 * 关闭数据库连接，并卸装线程绑定
	 * 
	 * @param conn
	 *            要关闭数据库连接实例
	 * @throws DaoException
	 */
	protected static void closeTxConnection(Connection conn) {
		if (conn != null) {
			try {
				tl.remove(); // 卸装线程绑定
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}

	public static Connection getConnection() {
		// 如果已经启用了事务
		if (isInTx()) {
			return tl.get();
		}
		// 传统得到连接
		Connection conn = null;
		try {
			Class.forName("org.sqlite.JDBC");
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		try {
			conn = DriverManager.getConnection("jdbc:sqlite:" + Config.DB_PATH);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return conn;
	}

	public static void beginBatch(Connection conn) throws SQLException {
		if (DBUtil.isInTx()) {
			return;
		} else {
			conn.setAutoCommit(false);

		}
	}

	public static void commitBatch(Connection conn) throws SQLException {
		if (DBUtil.isInTx()) {
			return;
		} else {
			conn.commit();
			conn.setAutoCommit(true);

		}
	}

	public static boolean isInTx() {
		return tl.get() != null;
	}

	public static void closeConnection(Connection conn) {
		// 如果已经启用了事务,不需要关闭，事务会控制是否关闭
		if (isInTx()) {
			return;
		}
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static void closeStatement(Statement... stmts) {
		for (Statement stmt : stmts) {
			try {
				if (null != stmt) {
					stmt.close();
				}

			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public static void closeResultSet(ResultSet... rses) {
		for (ResultSet rs : rses) {
			try {
				if (null != rs) {
					rs.close();
				}

			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}
}
